package com.wetool.jpa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import com.wetool.entity.Commodity;
import com.wetool.model.SearchParam;

/**
 * 商品信息查询规则
 * @author lixin
 */
public class CommoditySpec implements Specification<Commodity> {

	private final Long merchantId;
	private final SearchParam params;
	private final  Long[] categoryIds;

	public CommoditySpec(Long merchantId, SearchParam params, Long[] categoryIds) {
		this.merchantId = merchantId;
		this.params = params;
		this.categoryIds = categoryIds;
	}

	@Override
	public Predicate toPredicate(Root<Commodity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

		List<Predicate> predicates = new ArrayList<>();
		
		// 商家查询
		predicates.add(cb.equal(root.get("merchantId"), merchantId));
		
		//逻辑删除商品不展示
		predicates.add(cb.equal(root.get("isDeleted"), false));
		
		// 判断商品条码或名称
		if (StringUtils.isNotBlank(params.getKey())) {
			Predicate pred = cb.or(cb.like(cb.lower(root.get("name")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("barcode")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("pinyin")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("pinyinShorthand")), "%" + params.getKey() + "%"));
			predicates.add(pred);
		}
		if (params.getType() != null) {
			predicates.add(cb.equal(root.get("type"), params.getType()));
		}
		if (params.getType() == null && params.getUpdateTime() == null) {
			predicates.add(cb.notEqual(root.get("type"), 3L));
		}
		// 商品类型
		if (params.getCategoryId() != null) {
			Predicate pred = null;
			for(int l = 0 ; l < categoryIds.length ; l++) {
				if (l==0) {
					pred = cb.or(cb.equal(root.get("categoryId"),categoryIds[l]));//拼接sql null不能开头
				}
				pred = cb.or(pred,cb.equal(root.get("categoryId"),categoryIds[l]));
			}
			predicates.add(pred);
		}
		/* 长链接获取商品更新时间查询 */
		if (StringUtils.isNotEmpty(params.getUpdateTime())) {
			predicates.add(cb.greaterThanOrEqualTo(root.get("updateDate").as(String.class), params.getUpdateTime()));
			predicates.add(cb.lessThanOrEqualTo(root.get("updateDate"), new Date()));
		}
		
		// 创建时间比对
		// 日期格式大于
//		if (params.getFrom() != null) {
//			predicates.add(cb.greaterThan(root.get("createDate"), params.getFrom()));
//		}
//		if (params.getTo() != null) {
//			predicates.add(cb.lessThan(root.get("createDate"), params.getTo()));
//		}
		
		return andTogether(predicates, cb);
	}

	private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
		return cb.and(predicates.toArray(new Predicate[0]));
	}
}